package com.ericsson.enap.modules.cmdkpi.task;

import com.ericsson.common.domain.CollectBizTypeEnum;
import com.ericsson.common.pojo.InputStreamChannelExec;
import com.ericsson.common.quartz.task.ManualTask;
import com.ericsson.common.util.DateUtils;
import com.ericsson.common.util.EnipSshUtil;
import com.ericsson.common.util.LogFileName;
import com.ericsson.common.util.LoggerUtils;
import com.ericsson.enap.modules.cmdkpi.entity.CmdKpiDict;
import com.ericsson.enap.modules.cmdkpi.service.CmdKpiService;
import com.ericsson.enap.modules.cmdkpi.thread.CmdKpiThread;
import com.ericsson.enap.modules.sys.entity.EnipNetelement;
import com.ericsson.epc.modules.userebm.entity.EpcDictEBM;
import com.jcraft.enipjsch.ChannelExec;
import com.jcraft.enipjsch.JSch;
import com.jcraft.enipjsch.Session;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: 命令kpi 任务
 * @author: chenhongbo
 * @create: 2021-09-02 10:48
 */

@Component
public class CmdKpiTask  implements ManualTask {

    private Logger log = LoggerUtils.Logger(LogFileName.AmfCmdKpiJob);

    @Autowired
    private CmdKpiService cmdKpiService;

    public static String amfCollectionName = "vgckpi_16_amf";

    @Autowired
    private MongoTemplate mongoTemplate;

    public static Map<String,String> monthMap = new HashMap<>();

    static {
        monthMap.put("Jan", "01");
        monthMap.put("Feb", "02");
        monthMap.put("Mar", "03");
        monthMap.put("Apr", "04");
        monthMap.put("May", "05");
        monthMap.put("Jun", "06");
        monthMap.put("Jul", "07");
        monthMap.put("Aug", "08");
        monthMap.put("Sep", "09");
        monthMap.put("Oct", "10");
        monthMap.put("Nov", "11");
        monthMap.put("Dec", "12");
    }

    @Override
    public void execute() {

        //initKpiMap("10.245.90.104","falcomm","Er!css0n","pdc_kpi.pl -n 10 -i 5", "1");  //初始化执行一次

        deleteMongodbData(new Date());
        //amf
        CmdKpiDict ckd = new CmdKpiDict();
        ckd.setBizType(Integer.parseInt(CollectBizTypeEnum.VGCCmdKpi.value()));
        ckd.setNetType("1");

        Map<String, CmdKpiDict> dictMap = cmdKpiService.getCmdKpiDictList(ckd).stream().collect(Collectors.toMap(CmdKpiDict::getFormula, dict -> dict));
        List<EnipNetelement> netList = cmdKpiService.getNetList(1);
        for(EnipNetelement net : netList) {
            CmdKpiThread thread = new CmdKpiThread(dictMap,amfCollectionName,mongoTemplate,net,log);
            new Thread(thread).start();
        }

    }

    /**
     * 解析指令，初始化kpi表
     */
    private void initKpiMap(String ip,String username, String password,String cmd, String netType) {
        Session session = null;
        ChannelExec channelExec = null;
        BufferedReader input = null;
        //EnipSshUtil ssh = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(username, ip, 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.connect();
            session.openChannel("exec");
            channelExec =  (ChannelExec) session.openChannel("exec");
            channelExec.setCommand(cmd);
            channelExec.setInputStream(null);
            input = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
            channelExec.connect();

            System.out.println("指令执行成功");

            /*File file = new File("F:/amf_pdc_kpi.txt");
            input = new BufferedReader(new FileReader(file));*/

            /*ssh = new EnipSshUtil(ip,username,password);
            ssh.connect();

            InputStreamChannelExec Isce = ssh.execCommandReturnStream(cmd);
            input = new BufferedReader(Isce.getIs());*/

            List<CmdKpiDict> dictList = new ArrayList<>();
            String line;
            while ((line = input.readLine()) != null) {
                System.out.println(line);
                if (line.contains("NodeType")) {
                    String nodeType = line.substring(line.indexOf("NodeType") + 10);
                    String payloadUplink = "";
                    String payloadDownlink = "";
                    boolean containsPayload = false;
                    if (line.contains("Payload")) {
                        String[] arr = line.split("\\s{2,}");
                        payloadUplink = arr[1];
                        payloadDownlink = arr[2];
                        containsPayload = true;
                    }
                    String[] kpiKey = null;
                    while ((line = input.readLine()) != null) {
                        if (line.contains("Day")) {
                            kpiKey = line.split("\\s{2,}");
                            if ((containsPayload) && (line.contains("||"))) {
                                String[] subKpiKey = new String[8];
                                for (int i = 0; i < 8; i++) {
                                    if (i < 2) {
                                        subKpiKey[i] = kpiKey[i];
                                    } else if ((i >= 2) && (i < 5)) {
                                        subKpiKey[i] = (payloadUplink + " " + kpiKey[i]);
                                    } else {
                                        subKpiKey[i] = (payloadDownlink + " " + kpiKey[(i + 1)]);
                                    }
                                }
                                kpiKey = subKpiKey;
                            }
                           // System.out.println(Arrays.toString(kpiKey));

                            for(int i=2; i<kpiKey.length; i++) {
                                CmdKpiDict dict = new CmdKpiDict();
                                dict.setName(nodeType + " " + kpiKey[i]);
                                dict.setFormula(nodeType + " " + kpiKey[i]);
                                dict.setBizType(Integer.parseInt(CollectBizTypeEnum.VGCCmdKpi.value()));
                                dict.setNetType(netType);
                                dictList.add(dict);
                            }
                            break;
                        }
                    }

                }
            }
            System.out.println(dictList);
            cmdKpiService.initCmdKpiDict(dictList);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (channelExec != null && !channelExec.isClosed()) {
                channelExec.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }

    /**
     * 删除过期数据
     * @param now
     */
    private void deleteMongodbData(Date now){

        String deleteTime = DateUtils.getStatisTime(60*1440+30,now,"yyyy-MM-dd HH:mm:00");
        log.info("deleteTime-------------------------------:"+deleteTime);
        Query query = Query.query(Criteria.where("dateTime").lte(deleteTime));
        mongoTemplate.remove(query,amfCollectionName);


    }
}
